package com.goodmr.passport.webapp.Serivce.impl;

import com.goodmr.passport.account.AccountDao;
import com.goodmr.passport.account.PlatformModel;
import com.goodmr.passport.config.property.PasswordProperty;
import com.goodmr.passport.webapp.enums.ErrorEnum;
import com.goodmr.passport.webapp.exception.BadRequestException;
import lombok.NonNull;
import org.philcode.toolkit.core.util.RegexUtils;
import org.springframework.beans.factory.annotation.Autowired;

import java.util.Arrays;
import java.util.Collections;
import java.util.List;

/**
 * 帐号密码服务
 *
 * @author <a href="mailto:bingdong13@msn.com">bigo</a>
 */
abstract class AccountServiceImpl {

    @Autowired
    protected AccountDao accountDao;
    @Autowired
    private PasswordProperty passwordProperty;

    /**
     * 校验帐号合法性
     *
     * @param account 帐号
     */
    void validateAccount(String account) {

        // 校验帐号的合法性
        if (!RegexUtils.isMobile(account) && !RegexUtils.isEmail(account)) {

            throw new BadRequestException(ErrorEnum.ACCOUNT_FORMAT_ERROR);
        }
    }

    /**
     * 校验密码的合法性
     *
     * @param password 密码
     */
    void validatePassword(String password) {

        int minLength = passwordProperty.getMinLength();
        int maxLength = passwordProperty.getMaxLength();

        if (!RegexUtils.isSpecialPassword(password, minLength, maxLength)) {
            List<Object> args = Arrays.asList(minLength, maxLength);

            ErrorEnum.PASSWORD_FORMAT_ERROR.setArgs(args);

            throw new BadRequestException(ErrorEnum.PASSWORD_FORMAT_ERROR);
        }
    }

    /**
     * 校验验证码合法性
     *
     * @param account 帐号
     * @param code    验证码
     */
    void validateCode(@NonNull String account, @NonNull String code) {

        // todo 调用 verifyCodeService，做校验
    }

    /**
     * 获取帐号信息
     *
     * @param account 帐号
     * @return 返回帐号信息
     */
    PlatformModel getByAccount(@NonNull String account) {

        PlatformModel model = accountDao.findByOpenId(account);

        if (null == model || model.getAccountId() == 0) {

            ErrorEnum.ACCOUNT_NOT_EXIST.setArgs(Collections.singletonList(account));
            throw new BadRequestException(ErrorEnum.ACCOUNT_NOT_EXIST);
        }

        if (accountDao.isNormal(model.getId())) {

            ErrorEnum.ACCOUNT_NOT_NORMAL.setArgs(Collections.singletonList(account));
            throw new BadRequestException(ErrorEnum.ACCOUNT_NOT_NORMAL);
        }

        return model;
    }
}
